package logic

import (
	"context"
	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"patient/patientrpc/internal/svc"
	"patient/patientrpc/models/cache"
	"patient/patientrpc/models/mysql"
	"patient/patientrpc/patientrpc"
	"time"
)

type UserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserListLogic) UserList(in *patientrpc.UserListRequest) (*patientrpc.UserListResponse, error) {
	// todo: add your logic here and delete this line

	var users []mysql.User
	result, _ := cache.Rdb.Get(l.ctx, "userlist").Result()
	if result == "" {
		mysql.DB.Debug().Find(&users)
		marshal, _ := json.Marshal(users)

		cache.Rdb.Set(l.ctx, "userlist", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &users)
	}

	var userlist []*patientrpc.UserList
	for _, user := range users {
		list := patientrpc.UserList{
			UserId:  int64(user.ID),
			Account: user.Account,
		}
		userlist = append(userlist, &list)
	}
	return &patientrpc.UserListResponse{
		List: userlist,
	}, nil
}
